package audit

import (
	"encoding/json"
	"fmt"
)

func LoadAuditLogFromJson(data []byte) (*AuditLog, error) {
	ins := NewAuditLog()
	err := json.Unmarshal(data, ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

func NewAudit() *Audit {
	return &Audit{}
}

type Audit struct {
	Username  string `bson:"username" json:"username,omitempty" validate:"required"`
	ServiceId string `bson:"service_id" json:"service_id,omitempty" validate:"required"`
	Operate   string `bson:"operate" json:"operate,omitempty" validate:"required"`

	// 请求的具体内容
	Request string `bson:"request" json:"request,omitempty" validate:"required"`
}

func NewAuditLog() *AuditLog {
	return &AuditLog{}
}

type AuditLog struct {
	Audit `bson:",inline"`
	Id    string `bson:"id" json:"id" validate:"required"`
	Time  int64  `bson:"time" json:"time" validate:"required"`
}

func (a *AuditLog) String() string {
	return string(a.ToJsonByte())
}

func (a *AuditLog) ToJsonByte() []byte {
	b, err := json.Marshal(a)
	if err != nil {
		fmt.Println(err)
	}
	return b
}

func NewAuditLogSet() *AuditLogSet {
	return &AuditLogSet{
		Items: []*AuditLog{},
	}
}

type AuditLogSet struct {
	Total int64       `json:"total"`
	Items []*AuditLog `json:"items"`
}

func (a *AuditLogSet) Add(item *AuditLog) {
	a.Items = append(a.Items, item)
}
